<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.balanceId ? $t('brand.add') : $t('brand.revise')"
    :close-on-click-modal="false"
    :append-to-body="visible"
    class="component-manage-balance-add-or-update"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="auto"

      class="body-content"
      @submit.prevent
      @keyup.enter="onSubmit()"
    >
      <el-form-item
        :label="$t('distributionMsg.title')"
        :placeholder="$t('publics.titleNoEnter')"
        prop="balanceTitle"
        class="input-width"
      >
        <el-input
          v-model="dataForm.balanceTitle"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        :label="$t('user.rechargeAmount')"
        :placeholder="$t('user.enterRechargeAmount')"
        prop="rechargeAmount"
        style="width: 400px"
        class="input-width"
      >
        <el-input
          v-model="dataForm.rechargeAmount"
          :min="0.01"
          @change="onInputChange(1)"
          @input="dataForm.rechargeAmount = dataForm.rechargeAmount.replace(/^0*(?=\d)|[^\d.]/g,'')"
        />
      </el-form-item>
      <el-form-item
        v-if="paySettlementType!==1"
        :label="$t('user.rewardAmount')"
        prop="presAmount"
      >
        <el-input
          v-model="dataForm.presAmount"
          :placeholder="$t('user.enterRewardAmount')"
          min="0"
          max="100000000"
          class="input-width"
          @change="onInputChange(2)"
          @input="dataForm.presAmount = dataForm.presAmount.replace(/^0*(?=\d)|[^\d.]/g,'')"
        >
          <template #prepend>
            {{ $t("user.reward") }}
          </template>
          <template #append>
            {{ $t("home.amount") }}
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        :label="$t('user.rewardScore')"
        :placeholder="$t('user.enterRewardScore')"
        prop="presScore"
      >
        <el-input
          v-model="dataForm.presScore"
          min="0"
          max="100000000"
          class="input-width"
          @change="onInputChange(3)"
          @input="dataForm.presScore = dataForm.presScore.replace(/^0*(?=\d)|[^\d]/g,'')"
        >
          <template #prepend>
            {{ $t("user.reward") }}
          </template>
          <template #append>
            {{ $t("order.score") }}
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        :label="$t('user.rewardGrowthValue')"
        :placeholder="$t('user.enterRewardGrowthValue')"
        prop="presGrowth"
      >
        <el-input
          v-model="dataForm.presGrowth"
          min="0"
          max="100000000"
          class="input-width"
          @change="onInputChange(4)"
          @input="dataForm.presGrowth = dataForm.presGrowth.replace(/^0*(?=\d)|[^\d]/g,'')"
        >
          <template #prepend>
            {{ $t("user.reward") }}
          </template>
          <template #append>
            {{ $t("user.growth") }}
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        :label="$t('user.rewardCoupon')"
        prop="couponList"
      >
        <span>
          <div
            class="text-btn default-btn"
            @click="onConpouSelectHandle()"
          >{{ $t("user.selectCoupons") }}</div>
        </span>
        <el-table
          v-if="dataForm.couponList.length > 0"
          :data="dataForm.couponList"
          style="width: 100%"
        >
          <el-table-column
            :label="$t('marketing.couponName')"
            width="180"
          >
            <template #default="scope">
              <span style="margin-left: 10px">{{
                scope.row.couponName
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('user.couponUpperLimit')"
            width="140"
          >
            <template #default="scope">
              <span style="margin-left: 10px">{{ scope.row.limitNum }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('order.quantity')"
            min-width="170px"
          >
            <template #default="scope">
              <el-input-number
                v-model="scope.row.couponNum"
                :value-on-clear="1"
                :min="1"
                :max="scope.row.limitNum"
                size="small"
              />
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('publics.operating')"
            width="180"
          >
            <template #default="scope">
              <div
                class="text-btn default-btn"
                @click="onDeleteCoupon(scope.$index)"
              >
                {{ $t("brand.delete") }}
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item
        :label="$t('brand.sequence')"
        prop="seq"
      >
        <el-input-number
          v-model="dataForm.seq"
          controls-position="right"
          size="small"
          :value-on-clear="1"
          :min="1"
          :max="100"
          @change="onInputChange(5)"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span

        class="dialog-footer"
      >
        <div
          class="default-btn"
          @click="visible = false"
        >{{
          $t("remindPop.cancel")
        }}</div>
        <div
          class="primary-btn default-btn"
          @click="onSubmit()"
        >{{
          $t("remindPop.confirm")
        }}</div>
      </span>
    </template>
    <coupon-select
      v-if="couponSelectVisible"
      ref="couponSelectRef"
      :get-way="1"
      @refresh-select-coupon-list="onSelectDistributionCoupon"
    />
  </el-dialog>
</template>

<script setup>

import { ElMessage } from 'element-plus'
const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
let isSubmit = false
const dataForm = ref({
  balanceId: null,
  balanceTitle: null,
  rechargeAmount: 0,
  img: null,
  presAmount: 0,
  presScore: 0,
  presGrowth: 0,
  seq: 1,
  couponList: []
})
const couponSelectVisible = ref(false)

const validateTitle = (rule, value, callback) => {
  if (String(value).trim() === '') {
    callback(new Error($t('shop.titCanNoBlank')))
  } else {
    callback()
  }
}
const validateRechargeAmount = (rule, value, callback) => {
  if (Number(value) <= 0) {
    callback(new Error($t('shop.RechargeAmount')))
  } else {
    callback()
  }
}
const dataRule = {
  balanceTitle: [
    { required: true, message: $t('shop.titCanNoBlank'), trigger: 'blur' },
    { validator: validateTitle, trigger: 'blur' }
  ],
  rechargeAmount: [
    { required: true, message: $t('shop.RechargeAmount'), trigger: 'blur' },
    { validator: validateRechargeAmount, trigger: 'blur' }
  ]
}
// img: [
//   { required: true, message: $t('user.bgImgCannotEmpty'), trigger: 'blur' }
// ]

const allinpayStore = useAllinpayStore()
const paySettlementType = computed(() => {
  return allinpayStore.paySettlementType
})

const dataFormRef = ref(null)
const init = (balanceId) => {
  dataForm.value.balanceId = balanceId || 0
  visible.value = true
  isSubmit = false
  dataForm.value.balanceTitle = null
  dataForm.value.rechargeAmount = 0
  dataForm.value.img = null
  dataForm.value.presAmount = 0
  dataForm.value.presScore = 0
  dataForm.value.presGrowth = 0
  dataForm.value.seq = 1
  dataForm.value.couponList = []
  nextTick(() => {
    dataFormRef.value?.resetFields()
    if (dataForm.value.balanceId) {
      http({
        url: http.adornUrl('/user/userBalance/info/' + dataForm.value.balanceId),
        method: 'get',
        params: http.adornParams()
      }).then(({ data }) => {
        dataForm.value = data
      })
    }
  })
}
defineExpose({
  init
})
/**
 * 显示添加指定优惠券弹框
 */
const couponSelectRef = ref(null)
const onConpouSelectHandle = () => {
  couponSelectVisible.value = true
  nextTick(() => {
    couponSelectRef.value.init(dataForm.value.couponList)
  })
}
/**
 * 优惠券选择回调
 */
const onSelectDistributionCoupon = (coupons) => {
  // 初始化优惠券数量
  coupons.forEach(coupon => {
    coupon.couponNum = 1
    dataForm.value.couponList.forEach(item => {
      if (coupon.couponId === item.couponId) {
        coupon.couponNum = item.couponNum
      }
    })
  })
  // 更新优惠券列表数据
  if (coupons.length > 0) {
    dataForm.value.couponList = coupons
  } else {
    dataForm.value.couponList = []
  }
}
const onDeleteCoupon = (index) => {
  dataForm.value.couponList.splice(index, 1)
}
const onInputChange = (type) => {
  if (type === 1) {
    const amount = !dataForm.value.rechargeAmount ? 0.01 : checkNumber(dataForm.value.rechargeAmount, 1)
    dataForm.value.rechargeAmount = amount < 0.01 ? 0.01 : amount
  } else if (type === 2) {
    dataForm.value.presAmount = !dataForm.value.presAmount ? 0 : checkNumber(dataForm.value.presAmount, 1)
  } else if (type === 3) {
    dataForm.value.presScore = !dataForm.value.presScore ? 0 : checkNumber(dataForm.value.presScore, 2)
  } else if (type === 4) {
    dataForm.value.presGrowth = !dataForm.value.presGrowth ? 0 : checkNumber(dataForm.value.presGrowth, 2)
  } else if (type === 5) {
    dataForm.value.seq = !dataForm.value.seq ? 0 : checkNumber(dataForm.value.seq, 2)
  }
}
const checkNumber = (num, type) => {
  let reg = ''
  if (type === 1) {
    reg = /^[1-9]\d*$|^[1-9]\d*\.\d\d?$|^0\.\d\d?$/
    if (!reg.test(num)) {
      return 0
    } else if (num > 1000000) {
      return 1000000
    }
  } else {
    reg = /^[0-9]*$/
    if (!reg.test(num)) {
      return 0
    } else if (num > 1000000) {
      return 1000000
    }
  }
  return num
}
// 表单提交
const onSubmit = () => {
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      if (isSubmit) {
        return false
      }
      if (dataForm.value.rechargeAmount < 0.01) {
        ElMessage.error($t('marketing.moreThan0'))
        return false
      }
      dataForm.value.seq ??= 1
      isSubmit = true
      http({
        url: http.adornUrl('/user/userBalance'),
        method: dataForm.value.balanceId ? 'put' : 'post',
        data: http.adornData(dataForm.value)
      }).then(() => {
        ElMessage({
          message: $t('remindPop.succeeded'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            visible.value = false
            isSubmit = false
            emit('refreshDataList')
          }
        })
      })
    }
  })
}

</script>
<style lang="scss" scoped>
.component-manage-balance-add-or-update{
  .body-content{
  overflow: auto;
  }
  .input-width {
    width: 400px;
  }
  el-form-item {
    margin-bottom: 80px;
  }
}

</style>
